package math;

public class Line
{
	private Vector2D start, end;
	public Line(double sX, double sY, double eX, double eY)
	{
		start = new Vector2D(sX, sY);
		end = new Vector2D(eX, eY);
	}
	public Line(Vector2D start, Vector2D end)
	{
		this.start = start;
		this.end = end;
	}
	public Line()
	{
		start = end = null;
	}
	
	public Vector2D getStart()
	{
		return start;
	}
	public void setStart(Vector2D s)
	{
		start = s.clone();
	}
	public Vector2D getEnd()
	{
		return end;
	}
	public void setEnd(Vector2D e)
	{
		end = e.clone();
	}
	
	public Double getSlope()
	{
		return (start.getX() - end.getX() != 0) ? ((start.getY() - end.getY()) / (start.getX() - end.getX())) : null;
	}
	
	public Vector2D intersection(Line line)
	{
		Double slope1 = this.getSlope();
		Double slope2 = line.getSlope();
		
		if((slope1 == null && slope2 == null)) {return null;};
		if(slope1 != null && slope1.equals(slope2)) {return null; };
		if(slope1 == null)
		{
			double finalx = getStart().getX();
			double b_l = slope2 * -line.start.getX() + line.start.getY();
			double finaly = slope2 * finalx + b_l;
			return new Vector2D(finalx, finaly);
		}
		if(slope2 == null)
		{
			double finalx = line.getStart().getX();
			double b = slope1 * -start.getX() + start.getY();
			double finaly = slope1 * finalx + b;
			return new Vector2D(finalx, finaly);
		}
		
		double b = slope1 * -start.getX() + start.getY();
		double b_l = slope2 * -line.start.getX() + line.start.getY();
		 
		double finalx = (b - b_l) / (slope2 - slope1);
		double finaly = slope1 * finalx + b;
		
		return new Vector2D(finalx, finaly);
	}
}
